<template>
  <editor
      id="editor"
      v-model="content"
      :api-key="apiKey"
      :init="initConfig"
  />
</template>
<script>
import { fontFormats, plugins, toolbars } from './TEditor'
import Editor from '@tinymce/tinymce-vue'
import { downloadUrl, regexVideo } from '@/script/util'
import { uploadAttachment } from '@/services/util/util'

const apiKey = 'aaiu8u7yrq204xloul2q92mi0sdaneml86evmnvcrj0e3dqa'
const defaultConfig = {
  width: 1000,
  height: 600,
  menubar: true,
  language: 'zh_CN'
}

export default {
  name: 'TinyMce',
  components: {
    editor: Editor
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    config: {
      type: Object,
      default: () => {
        return {
          width: 1000,
          height: 600,
          menubar: true,
          language: 'zh_CN'
        }
      }
    }
  },
  data () {
    return {
      apiKey,
      content: '',
      initConfig: {
        plugins,
        toolbars,
        width: Object.assign(defaultConfig, this.config).width,
        height: Object.assign(defaultConfig, this.config).height,
        menubar: Object.assign(defaultConfig, this.config).menubar,
        language: Object.assign(defaultConfig, this.config).language,
        font_formats: fontFormats,
        images_upload_handler: async (blobInfo, successFun) => {
          const file = blobInfo.blob()
          const { url } = await this.uploadFile(file)
          successFun(url)
        },
        file_picker_types: 'media',
        file_picker_callback: (callback, value, meta) => {
          if (meta.filetype === 'media') {
            const input = document.createElement('input')
            input.setAttribute('type', 'file')
            const that = this // 为 Vue 构造函数中的 this，指向 Vue 实例对象
            input.onchange = async function () {
              const file = this.files[0] // 为 HTMLInputElement 构造函数中的 this，指向 input 实例对象
              const isValid = await that.validateVideo(file)

              if (isValid) {
                const { url } = await that.uploadFile(file)
                callback(url)
              } else {
                callback()
              }
            }

            input.click()
          }
        },
        /**
         * 视频上传成功回调方法
         * */
        video_template_callback: data => {
          return `<video width="745" height="420" controls="controls" src=${data.source} />`
        }
      }
    }
  },
  watch: {
    value: {
      handler (newValue) {
        if (newValue !== '') {
          this.content = newValue
        }
      },
      immediate: true
    }
  },
  methods: {
    /**
     * @description 获取富文本内容（注：供父组件调用）
     * @returns {string}
     */
    getContent () {
      return this.content
    },

    /**
     * @description 校验上传视频
     * @param {File} file - 要上传的文件
     * @returns {boolean}
     */
    async validateVideo (file) {
      if (!regexVideo.test(file.type)) {
        this.$message.error('请上传被支持的 视频 格式！')
        return false
      }
      const VideoSize = file.size / 1024 / 1024 < 500
      if (!VideoSize) {
        this.$message.error('上传视频大小限制 500M 以内！')
        return false
      }
      return true
    },
    /**
     * @description 获取视频时长
     * @param {File} file - 要上传的文件
     * @returns {Promise<number>}
     */
    getVideoDuration (file) {
      return new Promise(resolve => {
        const videoElement = document.createElement('video')
        videoElement.src = URL.createObjectURL(file)

        videoElement.addEventListener('loadedmetadata', () => {
          resolve(videoElement.duration)
        })
      })
    },

    /**
     * @description 上传文件
     * @param {File} file - 要上传的文件
     * @returns {Object}
     */
    async uploadFile (file) {
      const formData = new FormData()
      formData.append('files', file)
      let data
      await uploadAttachment(formData).then((res) => {
        if (res.code !== 10000) {
          this.$message.error('上传失败')
        }

        data = res.data
      })
      return {
        url: downloadUrl + data[0].attachNo,
        name: data[0].attachName
      }
    }
  }
}
</script>
